'''
https://leetcode.cn/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=top-interview-150
'''
from collections import deque
from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        if not root: return []
        res = []
        q = deque([root])
        while q:
            last = None
            for _ in range(len(q)):
                cur = q.popleft()
                last = cur
                if cur.left: q.append(cur.left)
                if cur.right: q.append(cur.right)
            res.append(last.val)
        return res
